package com.ruoyi.web.utils.tecentCos;

import com.ruoyi.web.utils.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.ruoyi.web.utils.tecentCos.MultipartFileToFile.multipartFileToFile;


/**
 * @ClassName CommonServiceImpl
 * @Description TODO
 * @Author cx
 * @Date 2019/9/10 12:31
 * @Version 2.0
 **/
@Transactional
@Service("commonService")
public class CommonServiceImpl implements CommonService {

    @Autowired
    TecentOssService tecentOssService;


    /**
     * 上传文件
     */
    @Override
    public HttpResponse uploadImage(HttpServletRequest request, String newFileName) throws Exception {

        UploadImageDTO result = new UploadImageDTO();

        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        // 判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
            // 转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            result.setImgUrl("");
            result.setImgUrlList(new ArrayList<>());

            if (multiRequest.getFileMap().size() == 1) {


                MultipartFile localFile = multiRequest.getFile("file");

//                File file = multipartFileToFile(localFile);
//                String results = tecentOssService.uploadFile(file,newFileName);
                String results = tecentOssService.uploadFileInput(localFile, newFileName);
//                delteTempFile(file);
                result.setImgUrl(results);
            } else if (multiRequest.getFileMap().size() == 0) {
                return HttpResponse.error("没有获取到数据！");
            } else {
                List<String> imgList = new ArrayList<>();
                Iterator<String> iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    // 取得上传文件
                    MultipartFile localFile = multiRequest.getFile(iter.next());
                    File file = multipartFileToFile(localFile);

                    String fileUrl = tecentOssService.uploadFile(file,newFileName);
                    imgList.add(fileUrl);
                }
                result.setImgUrlList(imgList);
            }
        } else {
            return HttpResponse.error("没有检测到数据！");
        }

        return HttpResponse.ok().setData(result);
    }


}
